import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE, approveStatus} from './constants';
import * as api from './api';
import moment from 'moment';

export const SET_DEFAULT_BRANDID = 'SET_DEFAULT_BRANDID';
export const setDefaultBrandId = (data = []) => dispatch => {
    if(data.length === 1)
        return dispatch({
            type: SET_DEFAULT_BRANDID,
            id: data[0].id
        });
    return null;
};
export const GET_BRANDS_BEGIN = 'GET_BRANDS_BEGIN';
export const GET_BRANDS_SUCCESS = 'GET_BRANDS_SUCCESS';
export const GET_BRANDS_FAIL = 'GET_BRANDS_FAIL';
export const getBrandBegin = () => ({
    type: GET_BRANDS_BEGIN
});
export const getBrandSuccess = data => ({
    type: GET_BRANDS_SUCCESS,
    data
});
export const getBrandFail = () => ({
    type: GET_BRANDS_FAIL,
});

export const getBrands = condition => dispatch => {
    dispatch(getBrandBegin());
    return api.getBrands(condition).then(res => {
        if(res.ok) {
            dispatch(setDefaultBrandId(res.data.content));
            dispatch(getBrandSuccess(res.data));
        } else
            dispatch(getBrandFail());
        return res.ok;
    });
};
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const brand = dispatch(getBrands());
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions, brand]).then(values => values[0] && values[1] && values[2]);
};
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    const {createTime, submitTime, approveTime, settlementTime, dealerCode, dealerName, subDealerCode, subDealerName, ...props} = condition;
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    if(submitTime && submitTime.length > 0) {
        props.beginSubmitTime = moment(submitTime[0]).toISOString();
        props.endSubmitTime = moment(submitTime[1]).toISOString();
    }
    if(approveTime && approveTime.length > 0) {
        props.beginApproveTime = moment(approveTime[0]).toISOString();
        props.endApproveTime = moment(approveTime[1]).toISOString();
    }
    if(settlementTime && settlementTime.length > 0) {
        props.beginSettlementTime = moment(settlementTime[0]).toISOString();
        props.endSettlementTime = moment(settlementTime[1]).toISOString();
    }
    dispatch(getListBegin());
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

/*=============================下发、提交================================= */
export const onClickSubmit = id => (dispatch, getState) => {
    const {
        rowVersion,
        submitedComment
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.submitInfo(id, {
        rowVersion,
        submitedComment
    });
};
/*==============================导出列表================================= */
export const exportData = () => (dispatch, getState) => {
    const queryCondition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    const {createTime, ...props} = queryCondition;
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    return api.exportInfo(props);
};

/*=============================作废================================= */
export const onClickAbandon = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.abandonInfo(id, {
        rowVersion
    }).then(res => res.ok);
};

/*==============================查询action================================= */
//修改查询条件

export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});


/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id).then(res => {
        if(res.ok) {
            const {details = [], ...props} = res.data;
            const conditions = details.map(item => {
                const {usedParts = []} = item;
                const newUsedParts = usedParts.map(m => ({
                    id: m.id,
                    usedPartBarCode: m.usedPartBarCode,
                    usedPartCode: m.usedPartCode,
                    usedPartName: m.usedPartName,
                    quantity: m.quantity,
                    usedPartDealCategory: m.usedPartDealCategory,
                    unit: m.unit,
                    remark: m.remark
                }));
                return {
                    claimId: item.claimId,
                    claimCode: item.claimCode,
                    claimSignedRemark: item.claimSignedRemark || 'NULL',
                    subDealerCode: item.subDealerCode || 'NULL',
                    subDealerName: item.subDealerName || 'NULL',
                    subClaimCode: item.subClaimCode || 'NULL',
                    supplierCode: item.supplierCode || 'NULL',
                    usedParts: newUsedParts,
                };
            });
            dispatch(getDetailSuccess({details: conditions,
                ...props}));
        } else
            dispatch(getDetailFail());
        return res.ok;
    });
};

/* =======================详情页作废================================== */
export const onClickAbandonForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.abandonInfo(id, {
        rowVersion
    });
};

/* =======================详情页提交================================== */
export const onClickSubmitForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.submitInfo(id, {
        rowVersion
    });
};

/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

/*=============================审核================================= */
export const onClickApprove = (id, data) => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    const {status, ...props} = data;
    switch(status) {
        case approveStatus.审核通过:
            return api.passInfo(id, {
                ...props,
                rowVersion
            }).then(res => res.ok);
        case approveStatus.不审核通过:
            return api.rejectInfo(id, {
                ...props,
                rowVersion
            }).then(res => res.ok);
        case approveStatus.驳回:
            return api.returnToPrevInfo(id, {
                ...props,
                rowVersion
            }).then(res => res.ok);
        default:
            return Promise.resolve(false);
    }
};

/*=============================确认================================= */
export const onClickConfirm = id => (dispatch, getState) => {
    const {
        rowVersion,
        attachments = [],
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.confirmInfo(id, {
        rowVersion,
        attachments
    }).then(res => res.ok);
};

/*==========================修改新增编辑页数据================================= */
export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';
export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});

export const onSubmit = id => (dispatch, getState) => {
    const {
        brandId,
        rowVersion,
        dealerId,
        supplierId,
        remark,
        details = [],
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    const detailsData = details.map(item => {
        const detail = item.usedParts;
        const usedParts = detail.map(m => ({
            id: m.id,
            remark: m.remark,
        }));
        return {
            claimId: item.claimId,
            usedParts,
        };
    });
    if(id)
        return api.updateInfo(id, {
            remark,
            rowVersion,
            details: detailsData,
        });
    return api.addInfo({
        brandId,
        dealerId,
        supplierId,
        remark,
        details: detailsData,
    });
};


export const getEditInitData = id => (dispatch, getState) => {
    const brands = getState().getIn(['page', 'domainData', 'brands', 'data']).toJS() || [];
    if(!id)
        return dispatch(setDefaultBrandId(brands));
    return dispatch(getDetail(id));
};

export const UPDATE_ATTACHMENTS = 'UPDATE_ATTACHMENTS';
export const updateAttachments = data => ({
    type: UPDATE_ATTACHMENTS,
    data: {
        fileId: data.id,
        fileName: data.fileName
    }
});

export const REMOVE_ATTACHMENTS = 'REMOVE_ATTACHMENTS';
export const removeAttachments = id => ({
    type: REMOVE_ATTACHMENTS,
    id
});


export const SELECT_DATA = 'SELECT_DATA';
export const selectData = data => ({
    type: SELECT_DATA,
    data
});

export const selectDealerForAdd = data => dispatch => {
    const condition = {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
        currency: data.currency,
        details: []
    };
    dispatch(selectData(condition));
};

export const selectDutyUnit = data => dispatch => {
    const condition = {
        supplierId: data.id,
        supplierCode: data.code,
        supplierName: data.name,
        details: []
    };
    dispatch(selectData(condition));
};
export const SELECT_CLAIM = 'SELECT_CLAIM';
export const selectClaim = (data = [], isAll) => (dispatch, getState) => {
    if(isAll) {
        const detailAlls = getState().getIn(['page', 'appState', 'submitData', 'details']).toJS();
        const {content = []} = data;
        const addconditions = [];
        content.map(item => {
            const {details = []} = item;
            const index = detailAlls.findIndex(v => v.claimId === item.id);
            if(index === -1) {
                const usedParts = details.map(m => ({
                    id: m.id,
                    usedPartBarCode: m.usedPartBarCode,
                    usedPartCode: m.usedPartCode,
                    usedPartName: m.usedPartName,
                    quantity: m.quantity,
                    usedPartDealCategory: m.usedPartDealCategory,
                    unit: m.unit,
                    remark: ''
                }));
                return addconditions.push({
                    claimId: item.id,
                    claimCode: item.code,
                    claimSignedRemark: item.claimSignedRemark || 'NULL',
                    subDealerCode: item.subDealerCode || 'NULL',
                    subDealerName: item.subDealerName || 'NULL',
                    subClaimCode: item.subClaimCode || 'NULL',
                    supplierCode: item.supplierCode || 'NULL',
                    usedParts,
                });
            }
            return item;
        });
        dispatch({
            type: SELECT_CLAIM,
            data: addconditions,
        });
    } else {
        const ids = data.map(item => item.id);
        if(!ids.length)
            return Promise.resolve(false);
        return api.getClaimDetails({
            ids,
        }).then(res => {
            if(res.ok) {
                const {content = []} = res.data;
                const conditions = content.map(item => {
                    const {details = []} = item;
                    const usedParts = details.map(m => ({
                        id: m.id,
                        usedPartBarCode: m.usedPartBarCode,
                        usedPartCode: m.usedPartCode,
                        usedPartName: m.usedPartName,
                        quantity: m.quantity,
                        usedPartDealCategory: m.usedPartDealCategory,
                        unit: m.unit,
                        remark: ''
                    }));
                    return {
                        claimId: item.id,
                        claimCode: item.code,
                        claimSignedRemark: item.claimSignedRemark || 'NULL',
                        subDealerCode: item.subDealerCode || 'NULL',
                        subDealerName: item.subDealerName || 'NULL',
                        subClaimCode: item.subClaimCode || 'NULL',
                        supplierCode: item.supplierCode || 'NULL',
                        usedParts,
                    };
                });
                dispatch({
                    type: SELECT_CLAIM,
                    data: conditions,
                });
            }
            return res.ok;
        });
    }
};

export const DELETE_DETAIL = 'DELETE_DETAIL';
export const deleteDetail = data => ({
    type: DELETE_DETAIL,
    data
});
export const DELETE_ALL_DETAIL = 'DELETE_ALL_DETAIL';
export const deleteAllDetail = () => ({
    type: DELETE_ALL_DETAIL
});

export const SELECT_DEALER = 'SELECT_DEALER';
export const selectDealer = data => ({
    type: SELECT_DEALER,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});

export const SELECT_SUBDEALER = 'SELECT_SUBDEALER';
export const selectSubDealer = data => ({
    type: SELECT_SUBDEALER,
    data: {
        subDealerId: data.id,
        subDealerCode: data.code,
        subDealerName: data.name,
    }
});

//新增搜索备件
export const SEARCH_IS = 'SEARCH_IS';
export const isSearch = data => ({
    type: SEARCH_IS,
    data
});

export const onSearch = value => (dispatch, getState) => {
    if(value) {
        const detailAlls = getState().getIn(['page', 'appState', 'submitData', 'details']).toJS();
        const addconditions = [];
        let newdetails = [];
        // eslint-disable-next-line array-callback-return
        detailAlls.map(item => {
            const {usedParts = []} = item;
            if(value.includes(',')) 
                value.split(',').forEach(c => {
                    usedParts.forEach(d => {
                        if(d.usedPartCode.includes(c.trim()))
                            return addconditions.push({
                                claimId: item.claimId,
                                claimCode: item.claimCode,
                                claimSignedRemark: item.claimSignedRemark || 'NULL',
                                subDealerCode: item.subDealerCode || 'NULL',
                                subDealerName: item.subDealerName || 'NULL',
                                subClaimCode: item.subClaimCode || 'NULL',
                                supplierCode: item.supplierCode || 'NULL',
                                usedParts: [d]
                            });
                    });
                });
            if(value.includes('，'))
                value.split('，').forEach(c => {
                    usedParts.forEach(d => {
                        if(d.usedPartCode.includes(c.trim()))
                            return addconditions.push({
                                claimId: item.claimId,
                                claimCode: item.claimCode,
                                claimSignedRemark: item.claimSignedRemark || 'NULL',
                                subDealerCode: item.subDealerCode || 'NULL',
                                subDealerName: item.subDealerName || 'NULL',
                                subClaimCode: item.subClaimCode || 'NULL',
                                supplierCode: item.supplierCode || 'NULL',
                                usedParts: [d]
                            });
                    });
                });
            newdetails = usedParts.filter(v => v.usedPartCode.includes(value.trim()));
            const newusedParts = newdetails.map(m => ({
                id: m.id,
                usedPartBarCode: m.usedPartBarCode,
                usedPartCode: m.usedPartCode,
                subDealerCode: m.subDealerCode,
                subDealerName: m.subDealerName,
                usedPartName: m.usedPartName,
                quantity: m.quantity,
                usedPartDealCategory: m.usedPartDealCategory,
                unit: m.unit,
                remark: m.remark
            }));
            if(newdetails.length > 0)
                return addconditions.push({
                    claimId: item.claimId,
                    claimCode: item.claimCode,
                    claimSignedRemark: item.claimSignedRemark || 'NULL',
                    subDealerCode: item.subDealerCode || 'NULL',
                    subDealerName: item.subDealerName || 'NULL',
                    subClaimCode: item.subClaimCode || 'NULL',
                    supplierCode: item.supplierCode || 'NULL',
                    usedParts: newusedParts
                });
        });
        dispatch({
            type: SEARCH_IS,
            data: {
                isSearch: true,
                newDetails: addconditions
            },
        });
    } else
        dispatch({
            type: SEARCH_IS,
            data: {
                isSearch: false,
                newDetails: []
            },
        });
};
